package com.xunlai.infra.permission.manager.authority.login;

import com.xunlai.infra.permission.manager.authority.exception.BadCaptchaException;
import com.xunlai.infra.permission.manager.authority.web.CaptchaStorage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.Objects;

/**
 * @author liang
 * @date 9/3/23 3:40 PM
 */
public class CaptchaAuthorizationProvider extends DaoAuthenticationProvider {

    private CaptchaStorage captchaStorage;

    public CaptchaAuthorizationProvider() {
    }

    public CaptchaAuthorizationProvider(CaptchaStorage captchaStorage) {
        this.captchaStorage = captchaStorage;
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if(authentication instanceof CaptchaUsernamePasswordAuthenticationToken authenticationToken){
            String captcha = authenticationToken.getCaptcha();
            String sessionId = RequestContextHolder.currentRequestAttributes().getSessionId();
            String code = captchaStorage.get(sessionId);
            code = code == null ? "" :code;
            if(!StringUtils.equalsIgnoreCase(captcha,code)){
                logger.error("captcha 校验失败," + captcha + ":" + code);
                throw new BadCaptchaException("验证码错误");
            }
            captchaStorage.remove(sessionId);
        }
        super.additionalAuthenticationChecks(userDetails, authentication);
    }

    public void setCaptchaStorage(CaptchaStorage captchaStorage) {
        this.captchaStorage = captchaStorage;
    }
}
